-- TalkingdataAgent
-- Created by chengb Jun/24/2016
-- Talkingdata 代理

module("TalkingdataAgent", package.seeall);

-- 常量定义
TakingdataConst = {
    REGISTER              = "qc_register";               -- 首次进入游戏
    ALCHEMIST_BUILDING    = "qc_alchemist_building";     -- 炼金坊建造建筑
    ALCHEMIST_GET_SLIME   = "qc_alchemist_get_slime";    -- 获得第一只冈布奥
    ENTER_NEWBIE_DUNGEON  = "qc_dungeon";                -- 进入新手迷宫
    CLEAR_NEWBIE_DUNGEON  = "qc_clear";                  -- 通关新手迷宫
    UNLOCK_ENDLESS        = "qc_unlock_endless";         -- 解锁迷宫无尽模式
    GET_SLIME_CAPTAIN     = "qc_get_slime_captain";      -- 获得舰长冈布奥
    UNLOCK_SKY_WAR        = "qc_unlock_sky_war";         -- 解锁天空之城
    BUY_SIGNBOARD         = "qc_buy_signboard";          -- 购买月卡
    CLICK_FORUM           = "qc_click_forum";            -- 点击论坛按钮
    WECHAT_SHARE_MAZE     = "qc_wechat_share_maze";      -- 迷宫完成后使用微信分享成功
    WECHAT_SHARE_SLIME    = "qc_wechat_share_slime";     -- 获得新冈布奥后使用微信分享成功
    WECHAT_SHARE_SETTINGS = "qc_wechat_share_settings";  -- 在设置界面中使用微信分享
    WECHAT_SHARE_AIRSHIP  = "qc_wechat_share_airship";    -- 获得飞艇后使用微信分享成功
    WEIBO_SHARE_MAZE      = "qc_weibo_share_maze";       -- 迷宫完成后使用微博分享成功
    WEIBO_SHARE_SLIME     = "qc_weibo_share_slime";      -- 获得新冈布奥后使用微博分享成功
    WEIBO_SHARE_SETTINGS  = "qc_weibo_share_settings";   -- 在设置界面中使用微博分享
    WEIBO_SHARE_AIRSHIP   = "qc_weibo_share_airship";    -- 获得飞艇后使用微博分享成功
    EGIN_SUBPACKAGE       = "qc_begin_subpackage";       -- 开始分包下载
    END_SUBPACKAGE        = "qc_end_subpackage";         -- 结束分包下载
}
local EVENT_PKG_DOWNLOAD_INFO    = "pkg_download_info";       -- 分包下载结果信息
local EVENT_INIT_DOWNLOAD_INFO   = "init_download_info";      -- 初始自动更新下载信息

-- 关注的炼金坊强化项
local CARE_WORKSHOP_ITEMS = { 1, 2 };

-- 新手关迷宫编号
local NEWBIE_DUNGEON_ID = 11;

-- 舰长冈布奥编号
local CAPTAIN_PET_ID = 57;

-- 月卡商品编号
local SUPERIOR_GOODS_ID = 5001;

-- 内部函数声明
local trackCustomEvent;
local trackLoginEvent;
local whenCreateNewChar;
local whenWorkshopStrengthen;
local whenWorkshopBuyEquip;
local whenStartDungeon;
local whenNextFloor;
local whenDungeonPass;
local whenGainPet;
local whenSkyRepair;
local whenBuyGoods;
local whenLoginOk;
local whenWeixinShareSucc;
local whenWeiboShareSucc;
local whenClickForum;
local whenPkgDownloadBegin;
local whenPkgDownloadEnd;

function init()
    cclog("TalkingdataAgent init.");

    EventMgr.removeAll("TalkingdataAgent");

    -- 关注玩家登录的事件
    EventMgr.register("TalkingdataAgent", event.LOGIN_OK, whenLoginOk);

    -- 关注创建角色的事件
    EventMgr.register("TalkingdataAgent", event.CREATE_NEW_CHAR, whenCreateNewChar);

    -- 关注炼金坊建筑强化事件
    EventMgr.register("TalkingdataAgent", event.WORKSHOP_STRENGTHEN, whenWorkshopStrengthen);

    -- 关注炼金坊购买装备的事件
    EventMgr.register("TalkingdataAgent", event.WORKSHOP_BUY_EQUIP, whenWorkshopBuyEquip);

    -- 关注玩家开始迷宫的事件
    EventMgr.register("TalkingdataAgent", event.START_DUNGEON, whenStartDungeon);

    -- 关注玩家进入下一层的事件
    EventMgr.register("TalkingdataAgent", event.NEXT_FLOOR, whenNextFloor);

    -- 关注通关迷宫的事件
    EventMgr.register("TalkingdataAgent", event.DUNGEON_PASS, whenDungeonPass);

    -- 关注获得冈布奥的事件
    EventMgr.register("TalkingdataAgent", event.GAIN_PET, whenGainPet);

    -- 关注修理天空之城飞艇的事件
    EventMgr.register("TalkingdataAgent", event.SKY_CITY_REPAIR, whenSkyRepair);

    -- 关注商城购买的事件
    EventMgr.register("TalkingdataAgent", event.BUY_GOODS, whenBuyGoods);

    -- 关注微信分享成功的事件
    EventMgr.register("TalkingdataAgent", event.WECHAT_SHARE_SUCC, whenWeixinShareSucc);

    -- 关注微博分享成功的事件
    EventMgr.register("TalkingdataAgent", event.WEIBO_SHARE_SUCC, whenWeiboShareSucc);

    -- 关注点击论坛的事件
    EventMgr.register("TalkingdataAgent", event.CLICK_FORUM, whenClickForum);

    -- 关注开始分包下载事件
    EventMgr.register("TalkingdataAgent", event.BEGIN_PKG_DOWNLOAD, whenPkgDownloadBegin);

    -- 关注完成分包下载事件
    EventMgr.register("TalkingdataAgent", event.END_PKG_DOWNLOAD, whenPkgDownloadEnd);
end

----------------------
--[[
--  TalkingData.callSdkFunc("setAccount", { "testAccount" }, "(Ljava/lang/String;)V");
--TalkingData.callSdkFunc("setAccountType", { "ANONYMOUS" }, "(Ljava/lang/String;)V");
--TalkingData.callSdkFunc("setGender", { "male" }, "(Ljava/lang/String;)V");
--TalkingData.callSdkFunc("onPurchase", { "item",10001, 330.4  }, "(Ljava/lang/String;IF)V");
--local jbString = json.encode({xxx=12, yyy="abc"});
--TalkingData.callSdkFunc("onEvent", { "event1", jbString }, "(Ljava/lang/String;Ljava/lang/String;)V");
--]]
--function callSdkFunc(method, args, sigs)
--    cclog("TalkingData callSdkFunc method: %s\n", method);
--
--    callJavaFuncWithClass("com.talkingdata.TalkingDataDelegate", method, args, sigs);
--end

-- 跟踪自定义事件
function trackCustomEvent(eventName, args)
    args = args or {};

    assert(type(eventName) =="string", "eventName必须为string类型");
    assert(type(args) == "table", "args必须为table类型");

    args["rid"] = "";
    if ME.user then
        args["rid"] = ME.user:getRid();
    end

    local jsonStr = json.encode(args);

    trace("TalkingdataAgent", "trackCustomEvent: eventName = %s, jsonStr = %s", eventName, jsonStr);

    if isAndroidPlatform() then
        -- 调用 talkingdata 的 java 接口
        callJavaFuncWithClass("com.talkingdata.TalkingDataDelegate", "onEvent",
            { eventName, jsonStr}, "(Ljava/lang/String;Ljava/lang/String;)V");
    elseif isIosPlatform() then
        callOCFuncWithClass("TalkingDataWrap", "trackCustomEvent", {
            eventId = eventName,
            parameters = jsonStr,
        });
    end
end

-- 跟踪登录事件
function trackLoginEvent(account)
    trace("TalkingdataAgent", "trackLoginEvent:account = %s", account);

    if isAndroidPlatform() then
        callJavaFuncWithClass("com.talkingdata.TalkingDataDelegate", "trackLoginEvent",
            {account, account, "ANONYMOUS"}, "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
       elseif isIosPlatform() then
        callOCFuncWithClass("TalkingDataWrap", "trackLoginEvent", {
            account = account,
        });
    end
end

-- 创建新角色的回调
function whenCreateNewChar(args)
    -- 跟踪新玩家首次登录事件
    trackCustomEvent(TakingdataConst.REGISTER);
end

-- 炼金坊强化成功的回调
function whenWorkshopStrengthen(args)
    local id    = args.id;
    local level = args.level;

    if table.indexOf(CARE_WORKSHOP_ITEMS, id) == -1 then
        return;
    end

    if level > 1 then
        return;
    end

    local eventName = string.format("%s_%d", TakingdataConst.ALCHEMIST_BUILDING, id);
    trackCustomEvent(eventName);
end

-- 炼金坊购买装备的回调
function whenWorkshopBuyEquip()
    trackCustomEvent(TakingdataConst.ALCHEMIST_GET_SLIME);
end

-- 玩家开始迷宫的回调
function whenStartDungeon(layer)
    local dungeonId = DungeonM.getDungeonId();
    if dungeonId ~= NEWBIE_DUNGEON_ID or layer ~= 1 then
        return;
    end

    local eventName = string.format("%s_%d.%d", TakingdataConst.ENTER_NEWBIE_DUNGEON, dungeonId, layer);
    local key = getUserKey(eventName);
    if UserDefaultM.getStringForKey(key) == "1" then
        -- 已经跟踪过了
        return;
    end

    UserDefaultM.setStringForKey(key, "1");
    trackCustomEvent(eventName);
end

-- 玩家进入下一层迷宫的回调
function whenNextFloor()
    local dungeonId = DungeonM.getDungeonId();
    if dungeonId ~= NEWBIE_DUNGEON_ID then
        return;
    end

    local layer = DungeonM.currentLayer();
    if layer ~= 2 then
        return;
    end

    local eventName = string.format("%s_%d.%d", TakingdataConst.ENTER_NEWBIE_DUNGEON, dungeonId, layer);
    local key = getUserKey(eventName);
    if UserDefaultM.getStringForKey(key) == "1" then
        -- 已经跟踪过了
        return;
    end

    UserDefaultM.setStringForKey(key, "1");
    trackCustomEvent(eventName);
end

-- 通关迷宫的回调
function whenDungeonPass(args)
    local dungeonId = args.dungeonId;

    -- 跟踪新手关通关的事件
    if dungeonId == NEWBIE_DUNGEON_ID then
        local eventName = string.format("%s_%d", TakingdataConst.CLEAR_NEWBIE_DUNGEON, dungeonId);
        trackCustomEvent(eventName);
        return;
    end

    local parentId = DungeonAreaM.getParentId(dungeonId);

    -- 跟踪解锁无尽模式的事件
    if DungeonAreaM.isAllSubAreaPassed(ME.user, parentId) then
        local eventName = string.format("%s_%d", TakingdataConst.UNLOCK_ENDLESS, parentId);
        trackCustomEvent(eventName);
    end
end

-- 获得冈布奥的回调
function whenGainPet(petId)
    if petId ~= CAPTAIN_PET_ID then
        return;
    end

    -- 跟踪获得舰长冈布奥的事件
    trackCustomEvent(TakingdataConst.GET_SLIME_CAPTAIN);
end

-- 修理天空之城飞艇的回调
function whenSkyRepair()
    -- 跟踪天空之城开启的事件
    trackCustomEvent(TakingdataConst.UNLOCK_SKY_WAR);
end

-- 商城购买的回调
function whenBuyGoods(args)
    local goodsId = args.goodsId;
    if goodsId == SUPERIOR_GOODS_ID then
        -- 跟踪购买月卡的事件
        trackCustomEvent(TakingdataConst.BUY_SIGNBOARD);
    end
end

-- 玩家登录游戏的回调
function whenLoginOk()
    local account = AccountM.getGamingAccount() or "";

    -- 跟踪登录事件
    trackLoginEvent(account);
end

-- 微信分享成功的回调
function whenWeixinShareSucc(args)
    local shareType = args.shareType;

    if shareType == SHARE_TYPE_GAME then
        trackCustomEvent(TakingdataConst.WECHAT_SHARE_SETTINGS)
    elseif shareType == SHARE_TYPE_DUNGEON then
        trackCustomEvent(TakingdataConst.WECHAT_SHARE_MAZE)
    elseif shareType == SHARE_TYPE_SLIME then
        trackCustomEvent(TakingdataConst.WECHAT_SHARE_SLIME)
    elseif shareType == SHARE_TYPE_AIRSHIP then
        trackCustomEvent(TakingdataConst.WECHAT_SHARE_AIRSHIP);
    end
end

-- 微博分享成功的回调
function whenWeiboShareSucc(args)
    local shareType = args.shareType;

    if shareType == SHARE_TYPE_GAME then
        trackCustomEvent(TakingdataConst.WEIBO_SHARE_SETTINGS)
    elseif shareType == SHARE_TYPE_DUNGEON then
        trackCustomEvent(TakingdataConst.WEIBO_SHARE_MAZE)
    elseif shareType == SHARE_TYPE_SLIME then
        trackCustomEvent(TakingdataConst.WEIBO_SHARE_SLIME)
    elseif shareType == SHARE_TYPE_AIRSHIP then
        trackCustomEvent(TakingdataConst.WEIBO_SHARE_AIRSHIP);
    end
end

-- 点击论坛的回调
function whenClickForum()
    trackCustomEvent(TakingdataConst.CLICK_FORUM);
end

-- 开始分包下载的回调
function whenPkgDownloadBegin()
    trackCustomEvent(TakingdataConst.BEGIN_SUBPACKAGE);
end

-- 结束分包下载的回调
function whenPkgDownloadEnd()
    trackCustomEvent(TakingdataConst.END_SUBPACKAGE);
end

-- 获取存储到UserDefault.xml中的key
function getUserKey(eventName)
    -- 增加"td"前缀，表示talkingdata的事件
    if ME.user then
        local rid = ME.user:getRid();
        return string.format("td_%s_%s", eventName, rid);
    else
        return "td_" .. eventName;
    end
end

